package org.example.config.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.example.datasource.eventhandler.EventHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class ZookeeperConfiguration {
    
    @Bean
    public CuratorFramework buildzkC() {
        String serverstring = "localhost:2181";
        int sessionTimeout = 5000;
        int connectionTimeout = 5000;
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
            .connectString(serverstring).sessionTimeoutMs(sessionTimeout).connectionTimeoutMs(connectionTimeout)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).namespace("").build();
        curatorFramework.start();
        return curatorFramework;
    }
    
    @Slf4j
    public static class ListenerContextService implements PathChildrenCacheListener{
        
//        private String eventType;
        private EventHandler dataHandler;
        public ListenerContextService(String eventType,EventHandler dataHandler) {
//            this.eventType = eventType;
            this.dataHandler = dataHandler;
            log.info("初始化ListenerContextService=>{}",eventType);
        }

        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            if(event.getData()!=null) {
                byte[] data = event.getData().getData();
                log.info("path=>{},data=>{}",event.getData().getPath(),data!=null?new String(event.getData().getData()):data);
            }
            switch (event.getType()) {
                case CHILD_ADDED:
                    dataHandler.addedNode(event);
                case CHILD_REMOVED:
                    dataHandler.deletedNode(event);
                case CHILD_UPDATED:
                    dataHandler.updatedNode(event);
                    break;
                default:
                    log.info("===========其他事件======{}======",event.getType());
                    break;
            }
        }
    }
}
